package org.example.casemodule.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.example.casemodule.api.UserInfoService;
import org.example.casemodule.dto.*;
import org.example.casemodule.entity.*;
import org.example.casemodule.enums.*;
import org.example.casemodule.mapper.*;
import org.example.casemodule.vo.*;
import org.example.common.pojo.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.casemodule.service.ILawyerService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.example.casemodule.vo.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 律师信息表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
public class LawyerServiceImpl extends ServiceImpl<LawyerMapper, LawyerEntity> implements ILawyerService {
    private static final Logger log = LoggerFactory.getLogger(LawyerServiceImpl.class);
    @Autowired
    private LawyerMapper lawyerMapper;
    @Autowired
    private LawyerCertificateMapper lawyerCertificateMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LawyerSpecialtyMapper lawyerSpecialtyMapper;
    @Autowired
    private LegalCaseMapper legalCaseMapper;
    @Autowired
    private CaseStatusLogMapper caseStatusLogMapper;
    @Autowired
    private CaseNotificationMapper caseNotificationMapper;
    @Autowired
    private CaseLawyerMapper caseLawyerMapper;
    @Autowired
    private SpecialtyMapper specialtyMapper;
    @Autowired
    private EvaluationMapper evaluationMapper;
    @Autowired
    private LawyerPreferenceMapper lawyerPreferenceMapper;
    @Autowired
    private LawyerScheduleMapper lawyerScheduleMapper;
    @Autowired
    private ScheduleEventMapper scheduleEventMapper;

    //律师资质审核
    @Override
    public LawyerAuditVO lawyerAudit(Long lawyerId, String status, Date effectiveDate) {

        //更新律师资质表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(LawyerCertificateEntity::getLawyerId, lawyerId);
        LawyerCertificateEntity lawyerCertificateEntity = lawyerCertificateMapper.selectOneByQuery(queryWrapper);
        lawyerCertificateEntity.setAuditStatus(CertificateAuditStatus.fromCode(status));
        lawyerCertificateEntity.setCreateTime(effectiveDate);
        lawyerCertificateMapper.update(lawyerCertificateEntity);

        //更新律师表
        queryWrapper = new QueryWrapper();
        queryWrapper.eq(LawyerEntity::getId, lawyerId);
        LawyerEntity lawyerEntity = lawyerMapper.selectOneByQuery(queryWrapper);
        if(CertificateAuditStatus.APPROVED.equals(status)){
            lawyerEntity.setIsCertified(1);
        }else{
            lawyerEntity.setIsCertified(0);
        }
        lawyerEntity.setCertificationTime(effectiveDate);
        lawyerMapper.update(lawyerEntity);


        LawyerAuditVO lawyerAuditVO = new LawyerAuditVO();
        lawyerAuditVO.setLawyerId(lawyerId);

        SysUser sysUser = userInfoService.getUserInfo(lawyerEntity.getUserId());
        lawyerAuditVO.setName(sysUser.getRealName());
        lawyerAuditVO.setNewStatus(lawyerEntity.getStatus());
        return lawyerAuditVO;
    }

    //获取律师信息
    @Override
    public LawyerInfoVO getLawyerInfo(Long lawyerId) {
        LawyerInfoVO lawyerInfoVO = new LawyerInfoVO();

        SysUser sysUser = userInfoService.getUserInfo(lawyerId);
        lawyerInfoVO.setLawyerId(lawyerId);
        lawyerInfoVO.setName(sysUser.getRealName());
        lawyerInfoVO.setContact(new LawyerInfoVO.Contact());
        lawyerInfoVO.getContact().setPhone(sysUser.getMobile());
        lawyerInfoVO.getContact().setEmail(sysUser.getEmail());

        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerId);
        lawyerInfoVO.setStatus(lawyerEntity.getStatus());

        //获取律师的执业领域代码
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(LawyerSpecialtyEntity::getLawyerId, lawyerId);
        List<LawyerSpecialtyEntity> lawyerSpecialtyEntities = lawyerSpecialtyMapper.selectListByQuery(queryWrapper);
        List<String> practiceAreas = lawyerSpecialtyEntities.stream().map(LawyerSpecialtyEntity::getSpecialtyCode).collect(Collectors.toList());

        lawyerInfoVO.setPracticeAreas(practiceAreas);

        //获取律师的证书信息
        queryWrapper = new QueryWrapper();
        queryWrapper.eq(LawyerCertificateEntity::getLawyerId, lawyerId);
        List<LawyerCertificateEntity> lawyerCertificateEntities = lawyerCertificateMapper.selectListByQuery(queryWrapper);
        List<LawyerInfoVO.Certificate> certificates = lawyerCertificateEntities.stream().map(lawyerCertificateEntity -> {
            LawyerInfoVO.Certificate certificate = new LawyerInfoVO.Certificate();
            certificate.setCertId(lawyerCertificateEntity.getId());
            certificate.setType(lawyerCertificateEntity.getCertName());
            certificate.setIssuer(lawyerCertificateEntity.getIssuer());
            certificate.setIssueDate(lawyerCertificateEntity.getIssueDate());
            certificate.setExpireDate(lawyerCertificateEntity.getExpireDate());
            certificate.setStatus(lawyerCertificateEntity.getAuditStatus());
            return certificate;
        }).collect(Collectors.toList());
        lawyerInfoVO.setCertificates(certificates);

        lawyerInfoVO.setRating(lawyerEntity.getServiceRating());

        return lawyerInfoVO;
    }

    //案件分配
    @Override
    public AssignVO getAssign(AssignDTO assignDTO) {
        AssignVO assignVO = new AssignVO();

        //更新案件表
        LegalCaseEntity legalCaseEntity = legalCaseMapper.selectOneById(assignDTO.getCaseId());
        if(legalCaseEntity != null){
            legalCaseEntity.setLawyerId(assignDTO.getLawyerId());
            legalCaseEntity.setAssignTime(new Date());
            legalCaseEntity.setStatus(CaseStatus.ASSIGNED.getCode());
            legalCaseMapper.update(legalCaseEntity);
        }else{
            log.error("案件不存在");
        }

        //更新律师表
        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(assignDTO.getLawyerId());
        if(lawyerEntity != null){
            lawyerEntity.setCasesTotal(lawyerEntity.getCasesTotal() + 1);
            lawyerMapper.update(lawyerEntity);
            int lawyerWorkload = lawyerEntity.getCasesTotal() - lawyerEntity.getCasesClosed();
            assignVO.setLawyerWorkload(lawyerWorkload);

        }


        //更新案件状态变更日志表
        CaseStatusLogEntity caseStatusLogEntity = new CaseStatusLogEntity();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(CaseStatusLogEntity::getCaseId, assignDTO.getCaseId());
        caseStatusLogEntity = caseStatusLogMapper.selectOneByQuery(queryWrapper);
        if(caseStatusLogEntity != null){
            caseStatusLogEntity.setNewStatus(CaseStatus.ASSIGNED.getCode());
            caseStatusLogEntity.setOperateTime(new Date());
            caseStatusLogEntity.setOperatorId(StpUtil.getLoginIdAsLong());
            if(assignDTO.getAssignType().equals("MANUAL")){
                caseStatusLogEntity.setRemark("手动分配案件，分配原因：" + assignDTO.getReason());
            }else{
                caseStatusLogEntity.setRemark("自动分配案件，分配原因：" + assignDTO.getReason());
            }
            caseStatusLogMapper.update(caseStatusLogEntity);
        }

        //更新案件通知表
        queryWrapper = new QueryWrapper();
        queryWrapper.eq(CaseNotificationEntity::getCaseId, assignDTO.getCaseId());
        CaseNotificationEntity caseNotificationEntity = caseNotificationMapper.selectOneByQuery(queryWrapper);
        if(caseNotificationEntity == null){
            caseNotificationEntity = new CaseNotificationEntity();
            caseNotificationEntity.setCaseId(assignDTO.getCaseId());
            caseNotificationEntity.setUserId(legalCaseEntity.getUserId());
            caseNotificationEntity.setSendTime(new Date());
            caseNotificationEntity.setNotificationType(NotificationType.ASSIGN.getCode());
            caseNotificationEntity.setContent("案件已分配给" + userInfoService.getUserInfo(assignDTO.getLawyerId()).getRealName());

            caseNotificationMapper.insert(caseNotificationEntity);
        }else{
            caseNotificationEntity.setSendTime(new Date());
            caseNotificationMapper.update(caseNotificationEntity);
        }

        //更新案件-律师关联表
        queryWrapper = new QueryWrapper();
        queryWrapper.eq(CaseLawyerEntity::getCaseId, assignDTO.getCaseId());
        CaseLawyerEntity caseLawyerEntity = caseLawyerMapper.selectOneByQuery(queryWrapper);
        if(caseLawyerEntity == null){
            caseLawyerEntity = new CaseLawyerEntity();
            caseLawyerEntity.setCaseId(assignDTO.getCaseId());
            caseLawyerEntity.setLawyerId(assignDTO.getLawyerId());
            caseLawyerEntity.setAssignTime(new Date());
            caseLawyerMapper.insert(caseLawyerEntity);
        }else{
            log.info("案件已分配");
        }

        assignVO.setAssignmentId(caseLawyerEntity.getId());
        assignVO.setCaseId(assignDTO.getCaseId());
        assignVO.setLawyerId(assignDTO.getLawyerId());
        // 设置案件预计开始时间为当前时间加上一个合理的处理时间（3个工作日）
        LocalDate estimatedStartDate = LocalDate.now().plusDays(3);
        assignVO.setEstimatedStartDate(Date.from(estimatedStartDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));

        return assignVO;
    }

    //律师状态修改
    @Override
    public LawyerStatusVO updateStatus(LawyerStatusDTO lawyerStatusDTO) {

        LawyerStatusVO lawyerStatusVO = new LawyerStatusVO();
        lawyerStatusVO.setLawyerId(lawyerStatusDTO.getLawyerId());
        lawyerStatusVO.setPreviousStatus(lawyerMapper.selectOneById(lawyerStatusDTO.getLawyerId()).getStatus());
        lawyerStatusVO.setCurrentStatus(lawyerStatusDTO.getNewStatus());
        lawyerStatusVO.setStatusChangeTime(new Date());

        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerStatusDTO.getLawyerId());
        lawyerEntity.setStatus(lawyerStatusDTO.getNewStatus());
        lawyerMapper.update(lawyerEntity);
        return lawyerStatusVO;
    }

    //律师搜索
    @Override
    public LawyerSearchVO getLawyerSearch(List<String> practiceAreas, Double minRating, Integer maxWorkload, Double minSuccessRate, String location) {
        LawyerSearchVO lawyerSearchVO = new LawyerSearchVO();

        lawyerSearchVO.setCriteria(new LawyerSearchVO.LawyerSearchCriteria());
        lawyerSearchVO.getCriteria().setPracticeAreas(practiceAreas);
        lawyerSearchVO.getCriteria().setMinRating(minRating);


        //按法律代码找名称
        List<String> practiceAreaNames = specialtyMapper.selectListByQuery(
                new QueryWrapper()
                        .in(SpecialtyEntity::getCode, practiceAreas)
        ).stream().map(SpecialtyEntity::getName).collect(Collectors.toList());

        //搜索律师
        QueryWrapper query = QueryWrapper.create()
                .where(
                        // 构建 OR LIKE 条件（匹配任意一个专业领域）
                        practiceAreaNames.stream()
                                .map(area -> "specialty LIKE '%" + area + "%'")
                                .collect(Collectors.joining(" OR "))
                )
                .and("service_rating >= ?", minRating)
                .and("(cases_total - cases_closed) <= ?", maxWorkload)
                .and("success_rate >= ?", minSuccessRate)
                .and("service_area LIKE ?", "%" + location + "%");

        List<LawyerEntity> lawyerEntities = lawyerMapper.selectListByQuery(query);

        lawyerSearchVO.setResults(lawyerEntities.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));
        return lawyerSearchVO;
    }
    private LawyerSearchVO.LawyerSearchResult convertToVO(LawyerEntity lawyerEntity) {
        LawyerSearchVO.LawyerSearchResult result = new LawyerSearchVO.LawyerSearchResult();
        result.setLawyerId(lawyerEntity.getId());
        result.setName(userInfoService.getUserInfo(lawyerEntity.getUserId()).getRealName());
        result.setRating(lawyerEntity.getServiceRating());
        result.setSuccessRate(lawyerEntity.getSuccessRate());
        result.setResponseTime("平均"+lawyerEntity.getAvgResponseHours()+"小时");
        result.setCurrentWorkload(lawyerEntity.getCasesTotal() - lawyerEntity.getCasesClosed());
        result.setSpecialties(lawyerEntity.getSpecialty());
        if(lawyerEntity.getStatus().equals(LawyerStatus.AVAILABLE))
            result.setAvailability("下周可接案");
        else
            result.setAvailability("忙碌");
        return result;
    }

    //律师绩效评估
    @Override
    public LawyerPerformanceVO getLawyerPerformance(Date period, List< Long> lawyerId) {
        LawyerPerformanceVO lawyerPerformanceVO = new LawyerPerformanceVO();
        lawyerPerformanceVO.setPeriod(period);

        lawyerPerformanceVO.setLawyers(lawyerId.stream()
                .map(this::getOneLawyerPerformance)
                .collect(Collectors.toList()));

        return lawyerPerformanceVO;
    }
    private LawyerPerformanceVO.LawyerPerformanceDetail getOneLawyerPerformance(Long lawyerId) {
        LawyerPerformanceVO.LawyerPerformanceDetail lawyerPerformanceDetail = new LawyerPerformanceVO.LawyerPerformanceDetail();
        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerId);
        lawyerPerformanceDetail.setLawyerId(lawyerId);
        lawyerPerformanceDetail.setName(userInfoService.getUserInfo(lawyerId).getRealName());
        lawyerPerformanceDetail.setCasesTotal(lawyerEntity.getCasesTotal());
        lawyerPerformanceDetail.setCasesCompleted(lawyerEntity.getCasesClosed());
        lawyerPerformanceDetail.setSuccessRate(lawyerEntity.getSuccessRate());
        lawyerPerformanceDetail.setAvgResponseHours(lawyerEntity.getAvgResponseHours());
        lawyerPerformanceDetail.setPerformanceLevel(lawyerEntity.getServiceRating());

        QueryWrapper query = QueryWrapper.create()
                .eq(EvaluationEntity::getLawyerId, lawyerId);
        EvaluationEntity evaluationEntity = evaluationMapper.selectOneByQuery(query);
        if(evaluationEntity != null) {
            lawyerPerformanceDetail.setClientRating(evaluationEntity.getRating());
            lawyerPerformanceDetail.setComparison(evaluationEntity.getContent());
        }

        return lawyerPerformanceDetail;
    }

    //律师档案归档
    @Override
    public LawyerProfileVO getLawyerProfile() {
        Long lawyerId = StpUtil.getLoginIdAsLong();
        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerId);

        LawyerProfileVO lawyerProfileVO = new LawyerProfileVO();
        lawyerProfileVO.setLawyerId(lawyerId);
        lawyerProfileVO.setName(userInfoService.getUserInfo(lawyerId).getRealName());
        lawyerProfileVO.setPracticeYears(lawyerEntity.getYearsOfPractice());

        List<LawyerSpecialtyEntity> lawyerSpecialtyEntities = lawyerSpecialtyMapper.selectListByQuery(
                new QueryWrapper()
                        .eq(LawyerSpecialtyEntity::getLawyerId, lawyerId)
        );
        lawyerProfileVO.setExpertise(lawyerSpecialtyEntities.stream().map(LawyerSpecialtyEntity::getSpecialtyCode).collect(Collectors.toList()));
        lawyerProfileVO.setIntroduction(lawyerEntity.getIntroduction());
        lawyerProfileVO.setContact(new LawyerProfileVO.Contact());
        lawyerProfileVO.getContact().setPhone(userInfoService.getUserInfo(lawyerId).getMobile());
        lawyerProfileVO.getContact().setEmail(userInfoService.getUserInfo(lawyerId).getEmail());

        lawyerProfileVO.setRating(lawyerEntity.getServiceRating());
        lawyerProfileVO.setAuditStatus(new LawyerProfileVO.AuditStatus());
        lawyerProfileVO.getAuditStatus().setProfile(lawyerEntity.getStatus());

        QueryWrapper query = QueryWrapper.create()
                .eq(LawyerCertificateEntity::getLawyerId, lawyerId);
        LawyerCertificateEntity lawyerCertificateEntity = lawyerCertificateMapper.selectOneByQuery(query);
        lawyerProfileVO.getAuditStatus().setCertificates(lawyerCertificateEntity.getAuditStatus());

        return lawyerProfileVO;
    }

    //律师档案修改
    @Override
    public int updateLawyerProfile(LawyerProfileDTO lawyerProfileDTO) {
       LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerProfileDTO.getLawyerId());
       lawyerEntity.setYearsOfPractice(lawyerProfileDTO.getPracticeYears());
       lawyerEntity.setIntroduction(lawyerProfileDTO.getIntroduction());
       lawyerMapper.update(lawyerEntity);

       SysUser sysUser = userInfoService.getUserInfo(lawyerProfileDTO.getLawyerId());
       sysUser.setMobile(lawyerProfileDTO.getContact().getPhone());
       sysUser.setEmail(lawyerProfileDTO.getContact().getEmail());
       userInfoService.updateUserInfo(sysUser);

        return 1;
    }

    //律师证书查询
    @Override
    public CertificatesVO getLawyerCertificates(){
        Long lawyerId = StpUtil.getLoginIdAsLong();
        List<LawyerCertificateEntity> lawyerCertificateEntities = lawyerCertificateMapper.selectListByQuery(
                new QueryWrapper()
                        .eq(LawyerCertificateEntity::getLawyerId, lawyerId)
        );
        CertificatesVO certificatesVO = new CertificatesVO();
        certificatesVO.setCertificates(lawyerCertificateEntities.stream().map(this::convertToCertificatesInfo).collect(Collectors.toList()));
        return certificatesVO;
    }
    private CertificatesVO.CertificatesInfo convertToCertificatesInfo(LawyerCertificateEntity lawyerCertificateEntity) {
        CertificatesVO.CertificatesInfo certificatesInfo = new CertificatesVO.CertificatesInfo();
        certificatesInfo.setCertId(lawyerCertificateEntity.getId());
        certificatesInfo.setCertName(lawyerCertificateEntity.getCertName());
        certificatesInfo.setIssuer(lawyerCertificateEntity.getIssuer());
        certificatesInfo.setIssueDate(lawyerCertificateEntity.getIssueDate());
        certificatesInfo.setExpireDate(lawyerCertificateEntity.getExpireDate());
        certificatesInfo.setFileUrl(lawyerCertificateEntity.getFileUrl());
        certificatesInfo.setStatus(lawyerCertificateEntity.getAuditStatus());
        return certificatesInfo;
    }


    //律师证书上传
    @Override
    public int updateLawyerCertificates(CertificatesDTO certificatesDTO) {
        //检查文件大小
        if(certificatesDTO.getFile().length() > 1024 * 1024 * 10) {
            throw new IllegalArgumentException("文件大小不能超过10MB");
        }
        Long lawyerId = StpUtil.getLoginIdAsLong();
        LawyerCertificateEntity lawyerCertificateEntity = new LawyerCertificateEntity();
        lawyerCertificateEntity.setLawyerId(lawyerId);
        lawyerCertificateEntity.setAuditStatus(CertificateAuditStatus.PENDING);
        lawyerCertificateEntity.setCertName(certificatesDTO.getCertName());
        lawyerCertificateEntity.setIssuer(certificatesDTO.getIssuer());
        lawyerCertificateEntity.setIssueDate(certificatesDTO.getIssueDate());
        lawyerCertificateEntity.setExpireDate(certificatesDTO.getExpireDate());
        lawyerCertificateEntity.setFileUrl(certificatesDTO.getFile());
        lawyerCertificateEntity.setCreateTime(new Date());
        lawyerCertificateMapper.insert(lawyerCertificateEntity);

        return 1;
    }

    //律师证书删除
    @Override
    public int deleteLawyerCertificates(Long Id) {
        //检查是否存在
        LawyerCertificateEntity lawyerCertificateEntity = lawyerCertificateMapper.selectOneById(Id);
        if(lawyerCertificateEntity == null) {
            throw new IllegalArgumentException("证书不存在");
        }

        //检查是否为执业证书
        if(lawyerCertificateEntity.getCertName().equals("律师执业证")) {
            throw new IllegalArgumentException("执业证书不能删除");
        }
        lawyerCertificateMapper.deleteById(Id);
        return 1;
    }

    //获取服务区域
    @Override
    public List<SpecialtyEntity> getExpertise() {
        //返回SpecialtyEntity的整张表的 数据
        QueryWrapper query = QueryWrapper.create()
                .select(SpecialtyEntity::getCode, SpecialtyEntity::getName)
                .from(SpecialtyEntity.class);
        return specialtyMapper.selectListByQuery(query);
    }

    //设置服务区域
    @Override
    public int setExpertise(ExpertiseDTO expertiseDTO) {
        Long lawyerId = StpUtil.getLoginIdAsLong();
        QueryWrapper query = QueryWrapper.create()
                .eq(LawyerPreferenceEntity::getLawyerId, lawyerId);
        LawyerPreferenceEntity lawyerPreferenceEntity = lawyerPreferenceMapper.selectOneByQuery(query);
        if(lawyerPreferenceEntity == null) {
            lawyerPreferenceEntity = new LawyerPreferenceEntity();
            lawyerPreferenceEntity.setLawyerId(lawyerId);
            lawyerPreferenceEntity.setCaseTypes(JSON.toJSONString(expertiseDTO.getExpertise()));
            lawyerPreferenceMapper.insert(lawyerPreferenceEntity);
        }
        lawyerPreferenceEntity.setCaseTypes(JSON.toJSONString(expertiseDTO.getExpertise()));
        lawyerPreferenceMapper.update(lawyerPreferenceEntity);
        return 1;
    }

    //获取律师评价
    @Override
    public Page<RatingVO> getLawyerRatings(Long page, Long size, String sort) {
        RatingVO ratingVO = new RatingVO();

        Long lawyerId = StpUtil.getLoginIdAsLong();
        ratingVO.setLawyerId(lawyerId);

        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerId);
        ratingVO.setAverageRating(lawyerEntity.getServiceRating());

        QueryWrapper query = QueryWrapper.create()
                .eq(EvaluationEntity::getLawyerId, lawyerId);
        ratingVO.setTotal(evaluationMapper.selectCountByQuery(query));

        // 分页查询评价数据
        Page<EvaluationEntity> evaluationPage = new Page<>(page, size);
        Page<EvaluationEntity> pagedEvaluationEntities = evaluationMapper.paginate(evaluationPage, query);

        List<EvaluationEntity> evaluationEntities = pagedEvaluationEntities.getRecords();

        // 评价分布（需要基于所有评价数据，而不是分页后的数据）
        List<EvaluationEntity> allEvaluationEntities = evaluationMapper.selectListByQuery(query);
        Map<String, Integer> ratingDistribution = allEvaluationEntities.stream()
                .collect(Collectors.groupingBy(
                        e -> String.valueOf(e.getRating()),
                        Collectors.summingInt(e -> 1)
                ));
        ratingVO.setRatingDistribution(ratingDistribution);

        List<RatingVO.Review> reviews = evaluationEntities.stream().map(evaluationEntity -> {
            RatingVO.Review review = new RatingVO.Review();
            review.setReviewId(evaluationEntity.getId());
            review.setCaseId(evaluationEntity.getCaseId());

            LegalCaseEntity legalCaseEntity = legalCaseMapper.selectOneById(evaluationEntity.getCaseId());
            if (legalCaseEntity != null) {
                review.setCaseName(legalCaseEntity.getTitle());
            }
            review.setRating(evaluationEntity.getRating());
            review.setComment(evaluationEntity.getContent());
            review.setDate(evaluationEntity.getEvaluateTime());

            review.setUserInfo(new RatingVO.UserInfo());
            review.getUserInfo().setUserId(evaluationEntity.getUserId());

            review.getUserInfo().setName(userInfoService.getUserInfo(evaluationEntity.getUserId()).getRealName());
            return review;
        }).collect(Collectors.toList());

        ratingVO.setReviews(reviews);

        // 创建并返回分页结果
        Page<RatingVO> pageList = new Page<>(page, size, ratingVO.getTotal());
        List<RatingVO> records = new ArrayList<>();
        records.add(ratingVO);
        pageList.setRecords(records);

        return pageList;
    }

    //获取律师结案偏好
    @Override
    public List<LawyerPreferenceEntity> getLawyerPreference() {
        Long lawyerId = StpUtil.getLoginIdAsLong();
        QueryWrapper query = QueryWrapper.create()
                .eq(LawyerPreferenceEntity::getLawyerId, lawyerId);
        return lawyerPreferenceMapper.selectListByQuery(query);
    }

    //设置律师结案偏好
    @Override
    public int setLawyerPreference(LawyerPreferenceDTO lawyerPreferenceDTO) {
        Long lawyerId = StpUtil.getLoginIdAsLong();
        QueryWrapper query = QueryWrapper.create()
                .eq(LawyerPreferenceEntity::getLawyerId, lawyerId);
        LawyerPreferenceEntity lawyerPreferenceEntity = lawyerPreferenceMapper.selectOneByQuery(query);
        if(lawyerPreferenceEntity == null) {
            lawyerPreferenceEntity = new LawyerPreferenceEntity();
            lawyerPreferenceEntity.setLawyerId(lawyerId);
            lawyerPreferenceEntity.setCaseTypes(JSON.toJSONString(lawyerPreferenceDTO.getCaseTypes()));
            lawyerPreferenceEntity.setMinAmount(lawyerPreferenceDTO.getMinAmount());
            lawyerPreferenceEntity.setMaxAmount(lawyerPreferenceDTO.getMaxAmount());
            lawyerPreferenceEntity.setDistricts(JSON.toJSONString(lawyerPreferenceDTO.getDistricts()));
            lawyerPreferenceEntity.setCreateTime(new Date());
            lawyerPreferenceMapper.insert(lawyerPreferenceEntity);
        }
        lawyerPreferenceEntity.setCaseTypes(JSON.toJSONString(lawyerPreferenceDTO.getCaseTypes()));
        lawyerPreferenceEntity.setMinAmount(lawyerPreferenceDTO.getMinAmount());
        lawyerPreferenceEntity.setMaxAmount(lawyerPreferenceDTO.getMaxAmount());
        lawyerPreferenceEntity.setDistricts(JSON.toJSONString(lawyerPreferenceDTO.getDistricts()));
        lawyerPreferenceEntity.setCreateTime(new Date());
        lawyerPreferenceMapper.update(lawyerPreferenceEntity);


        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(lawyerId);
        lawyerEntity.setAvgResponseHours(lawyerPreferenceDTO.getResponseTime());
        lawyerEntity.setServiceArea(lawyerPreferenceDTO.getDistricts().stream()
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.joining(",")));

        //按法律代码找名称
        List<String> practiceAreaNames = specialtyMapper.selectListByQuery(
                new QueryWrapper()
                        .in(SpecialtyEntity::getCode, lawyerPreferenceDTO.getCaseTypes())
        ).stream().map(SpecialtyEntity::getName).collect(Collectors.toList());
        lawyerEntity.setSpecialty(practiceAreaNames.stream().collect(Collectors.joining(",")));

        lawyerMapper.update(lawyerEntity);

        return 1;
    }

    //资料审核状态
    @Override
    public String getAuditStatus() {
        Long lawyerId = StpUtil.getLoginIdAsLong();
        LawyerCertificateEntity lawyerCertificateEntity = lawyerCertificateMapper.selectOneByQuery(
                new QueryWrapper()
                        .eq(LawyerCertificateEntity::getLawyerId, lawyerId)
        );

        return lawyerCertificateEntity.getAuditStatus().getInfo();
    }

    //获取服务时间
    @Override
    public ScheduleVO getSchedule() {
        Long lawyerId = StpUtil.getLoginIdAsLong();
        List<LawyerScheduleEntity> lawyerScheduleEntities = lawyerScheduleMapper.selectListByQuery(
                new QueryWrapper()
                        .eq(LawyerScheduleEntity::getLawyerId, lawyerId)
        );
        ScheduleVO scheduleVO = new ScheduleVO();
        scheduleVO.setWeeklySchedule(lawyerScheduleEntities.stream().map(lawyerScheduleEntity -> {
            ScheduleVO.WeeklySchedule weeklySchedule = new ScheduleVO.WeeklySchedule();
            weeklySchedule.setDayOfWeek(DayOfWeek.fromCode(lawyerScheduleEntity.getDayOfWeek().toString()));
            weeklySchedule.setTimeSlots(lawyerScheduleEntity.getStartTime() != null && lawyerScheduleEntity.getEndTime() != null ?
                    List.of(new ScheduleVO.TimeSlot(lawyerScheduleEntity.getStartTime().toString(), lawyerScheduleEntity.getEndTime().toString())) :
                    new ArrayList<>());
            return weeklySchedule;
        }).collect(Collectors.toList()));

        List<LegalCaseEntity> legalCaseEntities = legalCaseMapper.selectListByQuery(
                new QueryWrapper().select(LegalCaseEntity::getId)
                        .eq(LegalCaseEntity::getLawyerId, lawyerId)
        );
        //根据caseId查找ScheduleEvent
        List<ScheduleEventEntity> scheduleEventEntities = scheduleEventMapper.selectListByQuery(
                new QueryWrapper()
                        .in(ScheduleEventEntity::getCaseId, legalCaseEntities.stream().map(LegalCaseEntity::getId).collect(Collectors.toList()))
        );
        scheduleVO.setExceptions(scheduleEventEntities.stream().map(scheduleEventEntity -> {
            ScheduleVO.ExceptionSchedule exceptionSchedule = new ScheduleVO.ExceptionSchedule();
            exceptionSchedule.setDate(scheduleEventEntity.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            exceptionSchedule.setAvailable(false);
            exceptionSchedule.setReason(scheduleEventEntity.getTitle());
            return exceptionSchedule;
        }).collect(Collectors.toList()));
        return scheduleVO;
    }
}